const config = require('./config.js');
const path = require('path');
module.exports = class extends think.Controller {
	constructor(ctx) {
		super(ctx);
		this.wbuser = this.appModel("user", "wxbot");
		this.sgoods = this.appModel("goods", "sales");
		this.transfer = this.model("taoke/transfer");
		this.wxuser = this.model("weixin/user");
		this.goods = this.model("taoke/goods");
		this.qrcode = this.model("taoke/qrcode");
		this.user = this.model("system/user");
		this.asset = this.model("system/asset");
		this.score = this.model("system/score");
		this.money = this.model("system/money");
		this.message = this.model("system/message");
		this.order = this.model("taoke/order");
		this.agency = this.model("system/agency");
		this.queue = this.model("taoke/queue");

	}
	async __before() {

		let posts = this.post();
		console.log(posts.messageWxid2)
		
//		if(posts.messageWxid2) {
//			let allowRooms = ["10841944554@chatroom","5267654762@chatroom"];
//			if(posts.messageWxid2.indexOf("@chatroom") > -1 && allowRooms.indexOf(posts.messageWxid2) > -1) {
//				return false;
//			}
//		}

		console.log(posts);

		if(posts.messageWxid2 == 'newsapp') {
			return false;
		}

		const authResult = await this.fetch(`http://huitaor.cn/app/wxbot/api/auth?appid=${posts.appid}&appkey=${posts.appkey}&wxid=${posts.wxid}&`).then(res => res.json());
		if(authResult.errno == '1000'){
			return this.json(authResult);
		}

		if(posts.postType != 'crontab') {

			if(posts.postType == 'member') {
				let wbuser = await this.wbuser.where({
					wxid: posts.memberWxid
				}).find();

				let userInfo = {
					setup_id: wbsetup.id,
					wxid: posts.memberWxid,
					nickname: posts.memberNickname || wbuser.nickname,
					headimgurl: posts.memberHeadimg || wbuser.headimgurl,
					area: posts.memberArea || wbuser.area,
					sex: posts.memberSex || wbuser.sex

				};
				userInfo.nickname = think.emojiFilter(userInfo.nickname);
				await this.wbuser.where({
					wxid: posts.memberWxid
				}).update(userInfo);
				if(!think.isEmpty(wbuser.user_id)) {
					await this.user.where({
						id: wbuser.user_id
					}).update({
						nickname: userInfo.nickname
					});
				}

			}

			if(!think.isEmpty(posts.messageWxid2)) {

				let messageWxid = posts.messageWxid2;

				if(posts.messageWxid2.indexOf("@chatroom") > -1) {
					messageWxid = posts.messageWxid3;
				}

				let wbuser = await this.wbuser.where({
					wxid: messageWxid
				}).find();
				if(think.isEmpty(wbuser.user_id)) {

					if(posts.directive != 'bindUser') {

						if(wbsetup.type == 1) {
							const url = this.service("url");
							let qrcode_url = await url.create(`/app/wxmp/oauth/qrcode?id=1`);

							return this.fail(`未绑定公众号用户，请先关注公众号:${qrcode_url},在公众号底部菜单中点击获取用户号,将用户号信息发送给我绑定用户`);

						} else {
							let userInfo = {
								setup_id: wbsetup.id,
								wxid: messageWxid,
								nickname: posts.memberNickname || wbuser.nickname,
								headimgurl: posts.memberHeadimg || wbuser.headimgurl,
								area: posts.memberArea || wbuser.area,
								sex: posts.memberSex || wbuser.sex

							};
							if(!think.isEmpty(posts.memberInvite)) {
								let invite = await this.wbuser.where({
									wxid: posts.memberInvite
								}).find();
								let agencyid = await this.agency.where({
									user_id: invite.user_id
								}).getField("id", true);
								userInfo.agency_id = agencyid;
								wbuser.agency_id = agencyid;
							}
							await this.wbuser.bindUser(wbuser, userInfo);

						}

					}

				}

			}

		}

	}

	async messageAction() {
		let posts = this.post();
		if(posts.messageContent) {
			posts.messageContent.replace(/\*\|\*/g, "&");
		}

		if(posts.postType == 'crontab') {

			let time = new Date().valueOf() - 24 * 3600 * 1000;
			let messages = await this.message.where({
				is_notified: 0,
				create_time: ['>', time]
			}).select();
			let wxmessage = [];
			let wbsetup = this.wbsetup.where({
				wxid: posts.wxid
			}).find()
			messages.forEach(async(message) => {

				let wbuser = await this.wbuser.where({
					user_id: message.user_id,
					setup_id: wbsetup.id
				}).find();
				if(!think.isEmpty(wbuser)) {
					message.wxid = wbuser.wxid;
					wxmessage.push(message);
					await this.message.where({
						id: message.id
					}).update({
						is_notified: 1,
					});
				}

			});

			return this.success({
				type: 'text',
				content: wxmessage
			});

		}
		let messageWxid = posts.messageWxid2;
		if(posts.messageWxid2) {
			if(posts.messageWxid2.indexOf("@chatroom") > -1) {
				messageWxid = posts.messageWxid3;
			}

		}

		let wbuser = await this.wbuser.where({
			wxid: messageWxid
		}).find();
		let downUserInfo = 0;

		if(think.isEmpty(wbuser.nickname)) {
			downUserInfo = 1;
		}

		if(posts.directive == 'bindUser') {
			if(!think.isEmpty(wbuser.user_id)) {
				return this.fail(`已绑定用户,请勿重复操作`);
			}
			let openid = posts.messageContent.match(/[a-zA-Z0-9-_]+/)[0];

			let wxuser = await this.wxuser.where({
				openid: openid
			}).find();
			if(think.isEmpty(wxuser)) {
				const url = this.service("url");
				let qrcode_url = await url.create(`/app/wxmp/oauth/qrcode?id=1`);
				return this.fail(`公众号用户不存在，请先关注公众号：${qrcode_url}`);
			}
			let wbsetup = await this.wbsetup.where({
				appid: posts.appid,
				appkey: posts.appkey
			}).find();
			let userInfo = {
				setup_id: wbsetup.id,
				user_id: wxuser.user_id,
				wxid: messageWxid,
				create_time: new Date().valueOf(),
				nickname: posts.memberNickname || wbuser.nickname,
				headimgurl: posts.memberHeadimg || wbuser.headimgurl,
				area: posts.memberArea || wbuser.area,
				sex: posts.memberSex || wbuser.sex

			};

			if(think.isEmpty(wbuser)) {
				await this.wbuser.add(userInfo);
			} else {
				await this.wbuser.where({
					wxid: messageWxid
				}).update(userInfo);
			}
			return this.success({
				type: 'text',
				content: "与公众号用户绑定成功",
				downUserInfo: downUserInfo
			});

		}
		

		//提现
		if(posts.directive == 'getcash') {

			let data = await this.asset.getcash(wbuser.user_id);
			let msg = think.getInstance(data.data, config.getcash.tmpl[data.code]);
			return this.success({
				type: 'text',
				content: msg,
				downUserInfo: downUserInfo
			});

		}

		//余额

		if(posts.directive == 'balance') {
			let data = await this.asset.getbalance(wbuser.user_id);
			let msg = think.getInstance(data, config.balance.tmpl);
			return this.success({
				type: 'text',
				content: msg,
				downUserInfo: downUserInfo
			});

		}
		//邀请查询
		if(posts.directive == 'invite') {

			let data = await this.asset.getInvite(wbuser.user_id);
			let msg = think.getInstance(data, config.invite.tmpl);
			return this.success({
				type: 'text',
				content: msg,
				downUserInfo: downUserInfo
			});

		}
		//签到

		if(posts.directive == 'attend') {
			let data = await this.score.attend(wbuser.user_id);
			let msg = think.getInstance(data.data, config.attend.tmpl[data.code]);
			return this.success({
				type: 'text',
				content: msg,
				downUserInfo: downUserInfo
			});

		}
		//绑单

		if(posts.directive == 'bindOrder') {
			let orderNo = posts.messageContent;

			let data = await this.order.bindOrders(orderNo, wbuser.user_id);
			return this.success({
				type: 'text',
				content: data.errmsg,
				downUserInfo: downUserInfo
			});

		}
		//转化

		if(posts.directive == 'transfer') {

			let result = await this.transfer.getResult(wbuser.user_id, posts.messageContent);
			console.log(result);
			let msg = '';
			let type = 'text';
			if(!result) {
				msg = "该宝贝没有优惠策略";
			} else {

				if(config.transferType == 0) { //带淘口令文本
					msg = think.getInstance(result, config.transfer.tmpl[0]);
				}

				if(config.transferType == 1) { //图文链接
					result.wxid = messageWxid;
					msg = think.getInstance(result, config.transfer.tmpl[1]);
					type = 'link';

				}

				if(config.transferType == 2) { //带二维码图片

					result.qrcode_url = encodeURIComponent(`http://${this.ctx.host}/app/wxbot/goods/detail?goods_id=${result.goods_id}&wxid=${messageWxid}&source=1`);
					const snap = this.service("snap");
					let snapshot = await snap.create(`http://${this.ctx.host}/app/wxmp/oauth/pic?data=${JSON.stringify(result)}`, this.ctx.origin);
					console.log(snapshot);
					msg = snapshot;
					type = 'img';

				}
			}
			return this.success({
				type: type,
				content: msg,
				downUserInfo: downUserInfo
			});
		}

		//if(posts.directive == 'help' || posts.postType == 'friend') {
		if(posts.directive == 'help') {
			const url = this.service("url");
			let help_url = await url.create(`/app/wxbot/goods/help`);
			let data = {
				withdrawals_amount_limit: 10,
				help_url: help_url
			}
			let msg = think.getInstance(data, config.help.tmpl[config.transferType]);
			return this.success({
				type: 'text',
				content: msg,
				downUserInfo: downUserInfo
			});

		}

		if(posts.directive == 'search') {

			let keyword = posts.messageContent.slice(1);
			let data = await this.goods.search(keyword, wbuser.wxid, this.ctx.origin);
			let msg = think.getInstance(data, config.search.tmpl[1]);
			return this.success({
				type: 'link',
				content: msg,
				downUserInfo: downUserInfo
			});

		}

		if(posts.directive == 'share') {

			return this.success({
				type: 'card',
				content: config.share.tmpl,
				downUserInfo: downUserInfo
			});

		}

		if(posts.directive == 'directive') {
			let msg = think.getInstance(config.directive.data, config.directive.tmpl);
			return this.success({
				type: 'text',
				content: msg,
				downUserInfo: downUserInfo
			});

		}
		

	}
};